#
# Created by Administrator on 2021/8/14 AT 16:13.
#
from typing import List


class Solution:
    def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
        rank = [[n for _ in range(n)] for __ in range(n)]
        match = [n for _ in range(n)]
        for i in range(n):
            for j in range(n - 1):
                rank[i][preferences[i][j]] = j
        for [i, j] in pairs:
            match[i] = j
            match[j] = i
        unhappyCount = 0
        for x in range(n):
            y = match[x]
            index = rank[x][y]
            for i in range(index):
                u = preferences[x][i]
                v = match[u]
                if rank[u][x] < rank[u][v]:
                    unhappyCount += 1
                    break
        return unhappyCount


if __name__ == '__main__':
    sol = Solution()
    print(sol.unhappyFriends(n=4,
                             preferences=[[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]],
                             pairs=[[0, 1], [2, 3]]))
